package com.legendframework.core.dao.extension.service.ioc;

import com.legendframework.core.Store;
import com.legendframework.core.aop.AbstractProxy;
import com.legendframework.core.ioc.CommonBeansGenerate;
import com.legendframework.core.ioc.exception.BeansException;
import com.legendframework.core.AbstractLegendPlugin;
import com.legendframework.core.support.lang3.StringUtils;
import com.legendframework.core.dao.DataResources;
import com.legendframework.core.dao.Return;
import com.legendframework.core.dao.extension.service.IService;
import com.legendframework.core.dao.extension.service.ServiceGenerate;

import java.lang.annotation.Annotation;

/**
 * @see Service 方式的Bean注入类型
 */
public class ServiceBeansGenerate extends CommonBeansGenerate {

    public ServiceBeansGenerate(Store store) {
        super(store);
    }

    @Override
    public String getBeanName(Class<?> cls) {
        return StringUtils.isEmpty(cls.getAnnotation(Service.class).value()) ? cls.getName() : cls.getAnnotation(Service.class).value();
    }

    @Override
    public Class<? extends Annotation> getAnnotation() {
        return Service.class;
    }

    @Override
    protected Return<String, Object> newInstance(Class cls , AbstractLegendPlugin plugin) {
        try {
            if (!IService.class.isAssignableFrom(cls)) {
                throw new BeansException("这个类: '"+cls.getName()+"'需要是: '"+IService.class.getName()+"' 的子类");
            }
            //获取Bean名称
            String beanName = getBeanName(cls);
            String configDirectoryName = plugin.getSaveFileName().getConfigDirectoryName();
            if (StringUtils.isEmpty(configDirectoryName)) {
                configDirectoryName = plugin.getName();
            }
            //实例化
            DataResources config = new DataResources();
            config.setDataType(store.getDataResources().getDataType());
            config.setDataSource(store.getDataResources().getDataSource());
            config.setYamlParentPath(store.getDataResources().getYamlParentPath().endsWith(configDirectoryName) ? store.getDataResources().getYamlParentPath() : store.getDataResources().getYamlParentPath() +"/"+configDirectoryName);
            return Return.build(beanName,injectionBean(beanName,ServiceGenerate.generate(cls,config,store.getJdbcTransaction(),store.getYamlTransaction()),plugin));
        } catch (Throwable e) {
            throw new BeansException("构建Bean: ["+cls.getName()+"] 失败, 原因：'"+ e.getMessage()+"'",e);
        }

    }

    @Override
    protected AbstractProxy getProxyAop() {
        return store.getTransactionProxy().addTransaction(store.getYamlTransaction()).addTransaction(store.getJdbcTransaction());
    }
}
